import React, { useRef, useEffect } from "react";
import { connect } from "react-redux";
import * as actions from "@/store/actions/home";
import { HomeState } from "@/store/reducers/home";

import HomeHeader from "./components/HomeHeader";
import HomeSlider from "./components/HomeSlider";
import DogList from "./components/DogList";

import { loadMore, downRefresh, debounce } from "@/utils/debounce";
import { setSession, getSession } from "@/utils/storage";
import { message } from "antd";

import "./index.less";

const Home = (props: any) => {
  (window as any).push = props.history.push;
  const homeContainerRef = useRef(null);
  const dogListRef = useRef(null);
  useEffect(() => {
    let homeContainerCurrent = homeContainerRef.current as any;
    loadMore(homeContainerCurrent, props.getDogs);
    downRefresh(homeContainerCurrent, props.refreshDogs);

    homeContainerCurrent.addEventListener("scroll",debounce(()=>{
        let dogListForceUpdate=dogListRef.current as any
        dogListForceUpdate();
    }))

    if (props.dogs.list.length > 0) {
      // 切走在切回来保存滚动位置
      homeContainerCurrent.scrollTop = getSession("homeScrollTop") || 0;
    }
    
    return () => {
      setSession("homeScrollTop", homeContainerCurrent.scrollTop);
    };
  }, []);
  return (
    <>
      <HomeHeader
        currentCategory={props.currentCategory}
        setCurrentCategory={props.setCurrentCategory}
      />
      <div className="home-container" ref={homeContainerRef}>
        <HomeSlider {...props}></HomeSlider>
        <DogList
          ref={dogListRef}
          container={homeContainerRef}
          dogs={props.dogs}
          getDogs={props.getDogs}
          currentCategory={props.currentCategory}
        ></DogList>
      </div>
    </>
  );
};

function mapStateToProps(state: any): HomeState {
  return state.home as HomeState;
}

export default connect(mapStateToProps, actions)(Home);
